


#import "MMReachabilityViewController.h"
#import "Reachability.h"
#define LoadImgHeight  80.0f
#define MM_AnimationDuration    0.5f

@interface MMView : UIView

@property (atomic, assign) BOOL animating;


- (id)initWithView:(UIView*)view;
@end

@implementation MMView

@synthesize animating;

- (id)initWithView:(UIView *)view {
    
    self = [super initWithFrame:view.frame];
    if (self) {
        
        self.alpha = view.alpha;
        self.autoresizesSubviews = view.autoresizesSubviews;
        self.autoresizingMask = view.autoresizingMask;
        self.backgroundColor = view.backgroundColor;
        self.clearsContextBeforeDrawing = view.clearsContextBeforeDrawing;
        self.clipsToBounds = view.clipsToBounds;
        self.contentMode = view.contentMode;
        self.contentScaleFactor = view.contentScaleFactor;
        self.exclusiveTouch = view.exclusiveTouch;
        self.hidden = view.hidden;
        self.multipleTouchEnabled = view.multipleTouchEnabled;
        self.opaque = view.opaque;
        self.restorationIdentifier = view.restorationIdentifier;
        self.tag = view.tag;
        self.transform = view.transform;
        self.userInteractionEnabled = view.userInteractionEnabled;
    }
    
    return self;
}

- (void)setFrame:(CGRect)frame {
    
    if (!self.animating && self.frame.origin.y >= 0) {
        frame.origin.y = self.frame.origin.y;
    }
    
    [super setFrame:frame];
}

@end

static Reachability *_reachability = nil;
BOOL _reachabilityOn;

static inline Reachability* defaultReachability () {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _reachability = [Reachability reachabilityForInternetConnection];
#if !__has_feature(objc_arc)
        [_reachability retain];
#endif
    });
    
    return _reachability;
}

@interface MMReachabilityViewController ()

- (void)startInternetReachability;
- (void)stopInternerReachability;
- (void)checkNetworkStatus;
@end

@implementation MMReachabilityViewController {
    
    BOOL _loaded;
}

@synthesize bannerView = _bannerView;
@synthesize mode = _mode;
@synthesize visibilityTime;

- (void)dealloc {
    
    [self onDealloc];
    
#if !__has_feature(objc_arc)
    [super dealloc];
#endif
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    _connect = YES;
    _loaded = TRUE;
    [self.bannerView setHidden:YES];
//    [self.view addSubview:self.bannerView];
    
    

//    switch (self.mode) {
//            
//        default:
//        case MMReachabilityModeOverlay:
//        {
//            CGRect bannerFrame = self.bannerView.frame;
//            bannerFrame.origin.y = -self.bannerView.frame.size.height;
//            [self.bannerView setFrame:bannerFrame];
//            break;
//        }
//            
//        case MMReachabilityModeResize:
//        {
//            // replace the view controller view with an MMView
//            MMView *view = [[MMView alloc] initWithView:self.view];
//            NSArray *subviews = [self.view subviews];
//            for (UIView *subview in subviews) {
//                [view addSubview:subview];
//            }
//            
//            [self setView:view];
//            
//#if !__has_feature(objc_arc)
//            [view release];
//#endif
//            break;
//        }
//    }
    

}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self startInternetReachability];
    if (self.bannerView.superview == nil) {
        
        switch (self.mode) {
                
            default:
            case MMReachabilityModeOverlay:
            {
                [self.view addSubview:self.bannerView];
                [self.view bringSubviewToFront:self.bannerView];
                break;
            }
            
            case MMReachabilityModeResize:
                [self.view.superview addSubview:self.bannerView];
                [self.view.superview sendSubviewToBack:self.bannerView];
                break;
        }
    }
    
    //  the banner view is added after the viewDidLoad
    //  so we need to adjust the width in case of rotated interface
    CGRect bannerFrame = self.bannerView.frame;
    bannerFrame.size.width = self.view.frame.size.width;
    [self.bannerView setFrame:bannerFrame];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
}

#pragma mark - Public interface

- (void)onDealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self cancel];
}

#pragma mark - Properties overrides methods

- (UIView*)bannerView {
    
    if (!_bannerView) {
        
        UIView *noconnectionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
        [self setBannerView:noconnectionView];

        noconnectionView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
        
        UIImageView *loadImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,120,120)];
        loadImgView.center = CGPointMake(SCREEN_WIDTH/2-5,0.42*SCREEN_HEIGHT);
        loadImgView.image = [UIImage imageNamed:@"load_noconnection"];
        [noconnectionView addSubview:loadImgView];
        
        CGFloat loadImgViewY = CGRectGetMaxY(loadImgView.frame);
        
        UILabel *noConnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, loadImgViewY+10, self.view.frame.size.width, 21)];
        [noConnectionLabel setFont:[UIFont systemFontOfSize:16]];
        [noConnectionLabel setTextColor:[UIColor colorWithHexString:@"#8a8a8a"]];
        [noConnectionLabel setText:@"网络不给力哦..."];
        [noConnectionLabel setTextAlignment:NSTextAlignmentCenter];
        [noconnectionView addSubview:noConnectionLabel];
        
        CGFloat loadLableViewY = CGRectGetMaxY(noConnectionLabel.frame);
        
        UIButton *aginBtn = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-150)/2, loadLableViewY +25, 150, 30)];
        aginBtn.layer.cornerRadius = 5;
        aginBtn.layer.borderColor = MainColor.CGColor;
        aginBtn.layer.borderWidth = 1;
        aginBtn.backgroundColor = [UIColor whiteColor];
        aginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [aginBtn setTitle:@"重试" forState:UIControlStateNormal];
        [aginBtn setTitleColor:[UIColor colorWithHexString:@"#8a8a8a"] forState:UIControlStateNormal];
        [aginBtn addTarget:self action:@selector(updateRequest) forControlEvents:UIControlEventTouchUpInside];
        [noconnectionView addSubview:aginBtn];
    }
    
    return _bannerView;
}

-(void)updateRequest{
    NSLog(@"再次请求---");
}
- (void)setBannerView:(UIView*)bannerView {
    
    _bannerView = bannerView;
}

- (void)setMode:(MMReachabilityMode)mode {
    
    if (!_loaded) {
        _mode = mode;
    }
}

#pragma mark - Private methods

- (void)startInternetReachability {
    
    if (!_reachabilityOn) {
        _reachabilityOn = TRUE;
        [defaultReachability() startNotifier];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus) name:kReachabilityChangedNotification object:nil];
    
    [self checkNetworkStatus];
}

- (void)stopInternerReachability {
    
    _reachabilityOn = FALSE;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

- (void)showBanner {
   
    
    self.bannerView.hidden = NO;
//    __block CGRect viewFrame;
//    __block UIView *view = nil;
//    
//    switch (self.mode) {
//            
//        case MMReachabilityModeResize:
//        {
//            view = self.view;
//            if (view.frame.origin.y == 0) {
//                
//                ((MMView*)view).animating = TRUE;
//                
//                viewFrame = self.view.frame;
//                viewFrame.origin.y += self.bannerView.frame.size.height;
//                viewFrame.size.height -= self.bannerView.frame.size.height;
//            }
//            else
//                return;
//            break;
//        }
//            
//        default:
//        case MMReachabilityModeOverlay:
//        {
//            view = self.bannerView;
//
//            if (view.frame.origin.y == -view.frame.size.height) {
//                
//                viewFrame = view.frame;
//                viewFrame.origin.y += view.frame.size.height;
//                
//                [self.view bringSubviewToFront:view];
//            }
//            else
//                return;
//            break;
//        }
//    }
//    
//    [self.bannerView setHidden:NO];
//    
//    [UIView animateWithDuration:MM_AnimationDuration
//                          delay:0.0
//                        options:UIViewAnimationOptionBeginFromCurrentState
//                     animations:^{
//                         
//                         [view setFrame:viewFrame];
//                     }
//                     completion:^(BOOL finished) {
//                         
//                         if (self.mode == MMReachabilityModeResize) {
//                             ((MMView*)self.view).animating = FALSE;
//                         }
//                         
//                         if (self.visibilityTime > 0) {
//                             [self cancel];
//                             [self performSelector:@selector(hideBanner) withObject:nil afterDelay:self.visibilityTime];
//                         }
//                     }];
}

- (void)hideBanner {
    
    self.bannerView.hidden = YES;
    
//    __block CGRect viewFrame;
//    __block UIView *view = nil;
//    
//    switch (self.mode) {
//            
//        case MMReachabilityModeResize:
//        {
//            view = self.view;
//            if (view.frame.origin.y > 0) {
//                
//                ((MMView*)view).animating = TRUE;
//                viewFrame = self.view.frame;
//                viewFrame.origin.y -= self.bannerView.frame.size.height;
//                viewFrame.size.height += self.bannerView.frame.size.height;
//            }
//            else
//                return;
//            break;
//        }
//          
//        default:
//        case MMReachabilityModeOverlay:
//        {
//            view = self.bannerView;
//            if (view.frame.origin.y > -view.frame.size.height) {
//                
//                viewFrame = self.bannerView.frame;
//                viewFrame.origin.y = -view.frame.size.height;
//            }
//            else
//                return;
//            break;
//        }
//    }
//    
//    [UIView animateWithDuration:MM_AnimationDuration
//                          delay:0.0
//                        options:UIViewAnimationOptionBeginFromCurrentState
//                     animations:^{
//                         
//                         [view setFrame:viewFrame];
//                     }
//                     completion:^(BOOL finished) {
//                         
//                         [self.bannerView setHidden:YES];
//
//                         if (self.mode == MMReachabilityModeResize) {
//                             ((MMView*)self.view).animating = FALSE;
//                         }
//                     }];

}

- (void)checkNetworkStatus {
    
    // called after network status changes
    NetworkStatus internetStatus = [defaultReachability() currentReachabilityStatus];
    switch (internetStatus) {
            
        case NotReachable: {
            
            [self cancel];
            _connect = NO;
            [self performSelector:@selector(showReachability) withObject:nil afterDelay:0.1]; // performed with a small delay to avoid multiple notification causing stange jumping
            break;
        }
            
        case ReachableViaWiFi:
        case ReachableViaWWAN: {
            
            [self cancel];
            _connect = YES;
            [self performSelector:@selector(hideReachability) withObject:nil afterDelay:0.1]; // performed with a small delay to avoid multiple notification causing stange jumping
            break;
        }
            
        default:
            break;
    }
}

//扫一扫显示网络状态
-(void)showReachability{
    NSLog(@"无网络1 ->显示");
}
- (void)hideReachability{
    NSLog(@"有网络2 ->隐藏");
}

- (void)cancel {
    [MMReachabilityViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(showBanner) object:nil];
    [MMReachabilityViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideBanner) object:nil];
    
    [MMReachabilityViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(showReachability) object:nil];
    [MMReachabilityViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideReachability) object:nil];
}

@end
